package net.csdn.business.common.oauth2.component;

import net.csdn.business.common.oauth2.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;

/**
 * @Auther: zhangyalei
 * @Date: 2022/10/9 11:13
 * @Description: 登录时，防止同一账号登录，返回的token是同一个token，故写此类
 */
public class CustomAuthenticationKeyGenerator extends DefaultAuthenticationKeyGenerator {
    private static final String CLIENT_ID = "client_id";

    private static final String SCOPE = "scope";

    private static final String USERNAME = "username";

    private static final String DEVICE_ID = "device_id";

    @Override
    public String extractKey(OAuth2Authentication authentication) {
        Map<String, String> values = new LinkedHashMap<String, String>();
        OAuth2Request authorizationRequest = authentication.getOAuth2Request();
        if (!authentication.isClientOnly()) {
            values.put(USERNAME, authentication.getName());
        }
        values.put(CLIENT_ID, authorizationRequest.getClientId());
        if (authorizationRequest.getScope() != null) {
            values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<String>(authorizationRequest.getScope())));
        }
        Object principal=authentication.getPrincipal();
        if(principal instanceof LoginUser){
            LoginUser loginUser=(LoginUser) principal;
            String deviceId =loginUser.getDeviceId();
            if(StringUtils.isNotEmpty(deviceId)){
                values.put(DEVICE_ID, deviceId);
            }
        }
        return generateKey(values);
    }
}
